'use strict';
const db = uniCloud.database()
const $ = db.command.aggregate
const dbCmd = db.command
exports.main = async (event, context) => {
	//event为客户端上传的参数
	const {
		user_id, //用户id
		article_id, //文章id
		content, //评论内容
		comment_id = '',
		reply_id = '',
		is_reply = false //是否是子回复
	} = event

	let user = await db.collection('user').doc(user_id).get()
	user = user.data[0]
	//获取文章表
	const article = await db.collection('article').doc(article_id).get()
	//获取文章下的全部评论
	const comments = article.data[0].comments

	let commentObj = {
		comment_id: genID(5), //评论id
		comment_content: content, //评论内容
		create_time: new Date().getTime(), //评论时间
		is_reply: is_reply,
		author: {
			author_id: user._id, //评论者id
			author_name: user.author_name, //评论者昵称
			avatar: user.avatar, //评论者头像
			professional: user.professional, //评论者分区

		},
		replys: [] //回复
	}

	// 评论文章
	if (comment_id === '') {
		commentObj.replys = []
		commentObj = dbCmd.unshift(commentObj)
	} else {
		//回复其他用户评论
		//获得回复对象信息
		let commentIndex = comments.findIndex(item => {
			return item.comment_id === comment_id
		})
		let commentAuthor = ''


		//子回复
		if (is_reply) {
			commentAuthor = comments[commentIndex].replys.find(item=>item.comment_id === reply_id)
		} else {
			commentAuthor = comments.find(item => {
				return item.comment_id === comment_id
			})
		}

		commentAuthor = commentAuthor.author.author_name
		//回复给谁
		commentObj.to = commentAuthor
		//更新回复信息
		commentObj = {
			[commentIndex]: {
				replys: dbCmd.unshift(commentObj)
			}
		}
	}



	await db.collection('article').doc(article_id).update({
		comments: commentObj
	})

	//返回数据给客户端
	return {
		code: 200,
		msg: 'comment update success',
	}
};

function genID(length) {
	return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36)
	//tostring(num) 参数值--输出数基数 输出为num（2-36）进制
}
